package com.imut.lagain.repository;
import com.imut.lagain.entity.AnxietySession;
import org.slf4j.LoggerFactory;

import org.springframework.data.jpa.repository.JpaRepository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.data.jpa.repository.Modifying;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 焦虑安抚会话数据访问层
 */
@Mapper
public interface AnxietySessionRepository extends BaseMapper<AnxietySession> {

    /**
     * 根据用户ID查询活跃会话
     */
    @Select("SELECT a FROM AnxietySession a WHERE a.userId = :userId AND a.status = 'active' AND a.isDeleted = false")
    Optional<AnxietySession> findActiveSessionByUserId(@Param("userId") Long userId);

    /**
     * 根据用户ID查询所有会话
     */
    @Select("SELECT a FROM AnxietySession a WHERE a.userId = :userId AND a.isDeleted = false ORDER BY a.createdAt DESC")
    List<AnxietySession> findByUserId(@Param("userId") Long userId);

    /**
     * 根据用户ID和状态查询会话
     */
    @Select("SELECT a FROM AnxietySession a WHERE a.userId = :userId AND a.status = :status AND a.isDeleted = false ORDER BY a.createdAt DESC")
    List<AnxietySession> findByUserIdAndStatus(@Param("userId") Long userId, @Param("status") String status);

    /**
     * 根据用户ID和时间范围查询会话
     */
    @Select("SELECT a FROM AnxietySession a WHERE a.userId = :userId AND a.createdAt BETWEEN :startDate AND :endDate AND a.isDeleted = false ORDER BY a.createdAt DESC")
    List<AnxietySession> findByUserIdAndDateRange(@Param("userId") Long userId, 
                                                  @Param("startDate") LocalDateTime startDate, 
                                                  @Param("endDate") LocalDateTime endDate);

    /**
     * 根据用户ID和开始时间查询会话
     */
    @Select("SELECT a FROM AnxietySession a WHERE a.userId = :userId AND a.startTime >= :startTime AND a.isDeleted = false ORDER BY a.createdAt DESC")
    List<AnxietySession> findByUserIdAndStartTimeAfter(@Param("userId") Long userId, @Param("startTime") LocalDateTime startTime);

    /**
     * 根据会话ID查询会话
     */
    @Select("SELECT a FROM AnxietySession a WHERE a.id = :sessionId AND a.isDeleted = false")
    Optional<AnxietySession> findBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 完成会话
     */
    @Modifying
    @org.apache.ibatis.annotations.Update("UPDATE anxiety_session SET status = 'completed', end_time = #{endTime}, updated_at = #{updatedAt} WHERE id = #{sessionId}")
    int completeSession(@Param("sessionId") Long sessionId, 
                       @Param("endTime") LocalDateTime endTime, 
                       @Param("updatedAt") LocalDateTime updatedAt);

    /**
     * 更新会话的最终焦虑水平
     */
    @Modifying
    @org.apache.ibatis.annotations.Update("UPDATE anxiety_session SET final_anxiety_level = #{finalLevel}, updated_at = #{updatedAt} WHERE id = #{sessionId}")
    int updateFinalAnxietyLevel(@Param("sessionId") Long sessionId, 
                               @Param("finalLevel") Integer finalLevel, 
                               @Param("updatedAt") LocalDateTime updatedAt);

    /**
     * 统计用户会话数量
     */
    @Select("SELECT COUNT(a) FROM AnxietySession a WHERE a.userId = :userId AND a.isDeleted = false")
    Long countByUserId(@Param("userId") Long userId);

    /**
     * 统计用户完成的会话数量
     */
    @Select("SELECT COUNT(a) FROM AnxietySession a WHERE a.userId = :userId AND a.status = 'completed' AND a.isDeleted = false")
    Long countCompletedByUserId(@Param("userId") Long userId);

    /**
     * 查询用户最近的会话
     */
    @Select("SELECT a FROM AnxietySession a WHERE a.userId = :userId AND a.isDeleted = false ORDER BY a.createdAt DESC")
    List<AnxietySession> findRecentSessionsByUserId(@Param("userId") Long userId, org.springframework.data.domain.Pageable pageable);

    /**
     * 查询用户平均焦虑改善程度
     */
    @Select("SELECT AVG(a.initialAnxietyLevel - a.finalAnxietyLevel) FROM AnxietySession a WHERE a.userId = :userId AND a.status = 'completed' AND a.finalAnxietyLevel IS NOT NULL AND a.isDeleted = false")
    Double getAverageAnxietyImprovement(@Param("userId") Long userId);

    /**
     * 查询用户最常用的安抚技术
     */
    @Select("SELECT a.techniquesUsed FROM AnxietySession a WHERE a.userId = :userId AND a.techniquesUsed IS NOT NULL AND a.isDeleted = false")
    List<String> getTechniquesUsedByUserId(@Param("userId") Long userId);

    /**
     * 查询用户的焦虑触发器
     */
    @Select("SELECT a.trigger FROM AnxietySession a WHERE a.userId = :userId AND a.trigger IS NOT NULL AND a.isDeleted = false")
    List<String> getTriggersByUserId(@Param("userId") Long userId);

    /**
     * 查询超时未完成的会话
     */
    @Select("SELECT a FROM AnxietySession a WHERE a.status = 'active' AND a.startTime < :timeoutThreshold AND a.isDeleted = false")
    List<AnxietySession> findTimeoutSessions(@Param("timeoutThreshold") LocalDateTime timeoutThreshold);

    /**
     * 批量更新超时会话状态
     */
    @Modifying
    @org.apache.ibatis.annotations.Update("UPDATE anxiety_session SET status = 'timeout', updated_at = #{updatedAt} WHERE id IN (#{sessionIds})")
    int updateTimeoutSessions(@Param("sessionIds") List<Long> sessionIds, @Param("updatedAt") LocalDateTime updatedAt);
}
